<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入订单编号" v-model="listQuery.orderSn">
      </el-input>
      <el-select clearable class="filter-item" style="width: 200px;" placeholder="请选择订单状态" v-model="listQuery.value">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker clearable class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" v-model="tempAddTime" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="订单起始日期" end-placeholder="订单结束日期" align="right">
      </el-date-picker>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload" :loading="downloadLoading">导出</el-button>
      <el-button class="filter-item" type="primary" @click="logisticsQuery">物流查询</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row :default-sort="{prop: 'addTime', order: 'descending'}">

      <el-table-column align="center" min-width="100" label="订单编号" prop="orderSn" sortable>
      </el-table-column>

      <el-table-column align="center" label="订单状态" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag>{{scope.row.orderStatus | orderStatusFilter}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="订单金额" prop="goodsPrice" min-width="100px">
        <template slot-scope="scope">
          {{scope.row.goodsPrice + "元"}}
        </template>
      </el-table-column>

      <el-table-column align="center" label="支付金额" prop="actualPrice" min-width="100px">
        <template slot-scope="scope">
          {{scope.row.actualPrice + "元"}}
        </template>
      </el-table-column>

      <el-table-column align="center" label="支付时间" prop="payTime" sortable width="200px">
      </el-table-column>

      <el-table-column align="center" label="订单时间" prop="addTime" sortable width="200px">
      </el-table-column>

      <el-table-column align="center" label="物流单号" prop="shipSn" width="200px">
      </el-table-column>

      <el-table-column align="center" label="物流渠道" prop="shipChannel">
      </el-table-column>

      <el-table-column align="center" label="操作" width="245" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="primary" v-if="scope.row.orderStatus === 101" size="mini" @click="goPay(scope.row)">去付款</el-button>
          <el-button type="primary" v-if="scope.row.orderStatus === 101" size="mini" @click="cancelOrder(scope.row)">取消</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog width="800px" :visible.sync="orderDialogVisible">
      <el-form id="orderDialog" :data="orderDetail" label-position="left">
        <h1 class="orderDialogtitle" style="text-align:center;">爱联商圈</h1>
        <h3>订单详情</h3>
        <el-form-item label="订单编号">
          <span>{{ orderDetail.order.orderSn }}</span>
        </el-form-item>
        <el-form-item label="订单状态">
          <template slot-scope="scope">
            <el-tag>{{orderDetail.order.orderStatus | orderStatusFilter}}</el-tag>
          </template>
        </el-form-item>
        <el-form-item label="订单用户">
          <span>{{ nickname }}</span>
        </el-form-item>
        <el-form-item label="收货信息">
          <span>（收货人）{{ orderDetail.order.consignee }}</span>
          <span>（手机号）{{ orderDetail.order.mobile }}</span>
          <span>（地址）{{ orderDetail.order.address }}</span>
        </el-form-item>
        <el-form-item label="商品信息">
          <el-table size="small" :data="orderDetail.orderGoods" border fit highlight-current-row>
            <el-table-column align="center" label="商品名称" width="145" prop="goodsName" />
            <el-table-column align="center" label="商品编号" width="150" prop="goodsSn" />
            <el-table-column align="center" label="货品规格" width="100" prop="specifications" />

            <el-table-column align="center" label="积分" width="75" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-label type="primary" size="mini" v-if="scope.row.integralFlag==2">赠送</el-label>
                <el-label type="primary" size="mini">{{scope.row.integral}}</el-label>
              </template>
            </el-table-column>

            <el-table-column align="center" label="爱币" width="75" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-label type="primary" size="mini" v-if="scope.row.priceFlag==2">赠送</el-label>
                <el-label type="primary" size="mini">{{scope.row.price}}</el-label>
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="积分" prop="integral" />
          <el-table-column align="center" label="爱币" prop="price" /> -->
            <el-table-column align="center" label="货品数量" width="50" prop="number" />
            <el-table-column align="center" label="货品图片" width="100" prop="picUrl">
              <template slot-scope="scope">
                <img :src="scope.row.picUrl" width="40" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="费用信息">
          <span>
            ￥{{ orderDetail.order.goodsPrice }}
          </span>
        </el-form-item>
        <el-form-item label="支付信息">
          <span>（支付渠道）支付宝/微信</span>
          <span>（支付时间）{{orderDetail.order.payTime }}</span>
        </el-form-item>
        <el-form-item label="快递信息">
          <span>（快递公司）{{ orderDetail.order.shipChannel }}</span>
          <span>（快递单号）{{ orderDetail.order.shipSn }}</span>
          <span>（发货时间）{{ orderDetail.order.shipTime }}</span>
        </el-form-item>
        <el-form-item label="收货信息">
          <span>（确认收货时间）{{ orderDetail.order.confirmTime }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" id="orderDialogOut" @click="orderDialogOut()">打印</el-button>
      </div>
    </el-dialog>

    <el-dialog title="确认支付" :visible.sync="dialogChargeFormVisible">
      <el-card class="box-card">
        <h3>确认信息</h3>
        <el-form ref="walletRecoed" :model="walletRecoed" label-position="right" label-width="100px">
          <el-form-item label="订单编号" prop="recordSn">
            <el-input v-model="walletRecoed.recordSn" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="单价（元）" prop="retailPrice">
            <el-input v-model="tempRetailPrice" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="规格" prop="specifications">
            <el-input v-model="walletRecoed.specifications" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="number">
            <el-input v-model="tempNumber" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="运费" prop="freight">
            <el-input v-model="freight" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="总价（元）" prop="modifyAmount">
            <el-input v-model="walletRecoed.modifyAmount" :readonly="true"></el-input>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="box-card">
        <h3>支付方式</h3>
        <div id="example-4" style="margin-left:50px">
          <template>
            <el-radio v-model="walletRecoed.payType" label="2">
              <img :src="wxpay" alt="" class="abimg">
            </el-radio>
            <el-radio v-model="walletRecoed.payType" label="1" style="margin-left: 200px;">
              <img :src="zhifubaopay" alt="" class="abimg">
            </el-radio>
          </template>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleChargeCancel">取消</el-button>
        <el-button type="primary" @click="handleCharge" v-bind:disabled="chargeButton">支付</el-button>
      </div>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog title="微信支付" :visible.sync="qrDialogStatus" :close-on-click-modal=false width="250px" @close="handleChargeCancel">
      <vue-qr :text="qrConfig.value" :size="200" :margin="0"></vue-qr>
      <h3 style="color :red">注意：支付过程中，禁止刷新关闭浏览器！支付成功后系统会自动关闭二维码！</h3>
    </el-dialog>
    <!-- 添加对话框 -->
    <el-dialog title="支付宝支付" :visible.sync="alipayDialogStatus" :close-on-click-modal=false width="250px" @close="handleChargeCancel">
      <vue-qr :text="aliQrConfig.value" :size="200" :margin="0"></vue-qr>
      <h3 style="color :red">注意：支付过程中，禁止刷新关闭浏览器！支付成功后系统会自动关闭二维码！</h3>
    </el-dialog>
  </div>
</template>

<style>
.el-form-item {
  margin-bottom: 20px;
}
.abimg {
  position: absolute;
  margin-top: -15px;
  height: 40px;
}
</style>

<script>
import { orderList, orderTotallist, orderDetail, cancalOrder, ordersList, modifyOrder } from '@/api/order'
import { createUser, chargeByAliPay, readMechanismUser } from '@/api/goods'
import { queryalipaystatus } from '@/api/user'
import store from '@/store'
import VueQr from 'vue-qr'
import wxpay from '@/assets/image/wxpay.png'
import zhifubaopay from '@/assets/image/zhifubaopay.png'

const statusMap = {
  101: '未付款',
  102: '用户取消',
  103: '系统取消',
  201: '已付款',
  202: '申请退款',
  203: '已退款',
  301: '已发货',
  401: '用户收货',
  402: '系统收货',
  501: '用户评价',
  502: '用户追评'
}

export default {
  name: 'order',
  components: { VueQr },
  data() {
    return {
      wxpay,
      zhifubaopay,
      unShipOrder: 0,
      list: undefined,
      total: undefined,
      listLoading: true,
      qrDialogStatus: false,
      alipayDialogStatus: false,
      dialogChargeFormVisible: false,
      chargeButton: false,
      qrConfig: {
        value: ''
      },
      aliQrConfig: {
        value: ''
      },
      options: [
        {
          value: '101',
          label: '未付款'
        },
        {
          value: '102',
          label: '用户取消'
        },
        {
          value: '103',
          label: '系统取消'
        },
        {
          value: '201',
          label: '已付款'
        },
        {
          value: '202',
          label: '申请退款'
        },
        {
          value: '203',
          label: '已退款'
        },
        {
          value: '301',
          label: '已发货'
        },
        {
          value: '401',
          label: '用户收货'
        },
        {
          value: '402',
          label: '系统收货'
        },
        {
          value: '501',
          label: '用户评价'
        },
        {
          value: '502',
          label: '用户追评'
        }
      ],
      listQuery: {
        page: 1,
        limit: 20,
        orderSn: '',
        id: undefined,
        name: undefined,
        addTime: undefined,
        orderStatusArray: [],
        value: '',
        sort: 'add_time',
        order: 'desc'
      },
      tempAddTime: undefined,
      statusMap,
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        orderGoods: [],
        mechanism: {}
      },
      ordersDetail: {
        order: {},
        orderGoods: {}
      },
      nickname: '',
      shipForm: {
        receiverName: undefined,
        receiverMobile: undefined,
        receiverProvinceName: undefined,
        receiverCityName: undefined,
        receiverExpAreaName: undefined,
        receiverAddress: undefined,
        goodsName: undefined,
        orderCode: undefined,
        shipper: '0',
        shipperCode: 'SF',
        payType: '1',
        expType: '2',
        quantity: '1'
      },
      shipDialogVisible: false,
      refundForm: {
        orderId: undefined,
        recordSn: undefined,
        refundIntegral: undefined,
        refundMoney: undefined
      },
      refundDialogVisible: false,
      downloadLoading: false,
      walletRecoed: {
        userId: undefined,
        recordSn: '',
        modifyAmount: '',
        modifyResource: store.getters.mechanismId,
        payType: '2',
        type: '6',
        specifications: '',
        number: ''
      },
      tempRetailPrice: 0,
      tempNumber: 0,
      freight: 0,
      listQuery_1: {
        mechanismId: store.getters.mechanismId,
        mobile: '',
        orderId: undefined
      },
      tempOrderSn: '',
      orderSn: '',
      orderId: undefined,
      pickerOptions: {
        shortcuts: [
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '前天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status]
    }
  },
  created() {
    this.listQuery.orderSn = this.$route.params.orderSn
    this.getList()
  },
  beforeDestroy: function() {
    clearInterval(this.interval)
  },
  methods: {
    getList() {
      this.listLoading = true
      if (this.tempAddTime !== undefined && this.tempAddTime !== null) {
        this.listQuery.addTime = this.tempAddTime.toString()
      }
      orderList(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listQuery.addTime = null
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listQuery.addTime = null
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleDetail(row) {
      orderDetail(row.id).then(response => {
        this.orderDetail = response.data.data
        this.nickname = this.orderDetail.mechanismUser.username
      })
      this.orderDialogVisible = true
    },
    orderDialogOut() {
      var Output = document.getElementById('orderDialog')
      var newContent = Output.innerHTML
      document.body.innerHTML = newContent
      window.print()
      window.location.reload()
      return false
    },
    handleDownload() {
      if (this.tempAddTime !== undefined && this.tempAddTime !== null) {
        this.listQuery.addTime = this.tempAddTime.toString()
      }
      import('@/vendor/Export2Excel').then(excel => {
        orderTotallist(this.listQuery).then(response => {
          const tHeader = [
            '订单ID',
            '订单编号',
            '订单状态',
            '实付人民币（元）',
            '支付时间',
            '订单时间',
            '是否删除',
            '收货人',
            '收货联系电话',
            '收货地址'
          ]
          const filterVal = ['id', 'orderSn', 'orderStatus', 'actualPrice', 'payTime', 'addTime', 'deleted', 'consignee', 'mobile', 'address']
          const list = response.data.data.items
          for (var i = 0; i < list.length; i++) {
            if (list[i].orderStatus === 101) list[i].orderStatus = '未付款'
            else if (list[i].orderStatus === 102) list[i].orderStatus = '用户取消'
            else if (list[i].orderStatus === 103) list[i].orderStatus = '系统取消'
            else if (list[i].orderStatus === 201) list[i].orderStatus = '已付款'
            else if (list[i].orderStatus === 202) list[i].orderStatus = '申请退款'
            else if (list[i].orderStatus === 203) list[i].orderStatus = '已退款'
            else if (list[i].orderStatus === 301) list[i].orderStatus = '已发货'
            else if (list[i].orderStatus === 401) list[i].orderStatus = '用户收货'
            else if (list[i].orderStatus === 402) list[i].orderStatus = '系统收货'
            else if (list[i].orderStatus === 501) list[i].orderStatus = '用户评价'
            else if (list[i].orderStatus === 502) list[i].orderStatus = '用户追评'

            if (list[i].deleted === false) list[i].deleted = '否'
            else if (list[i].deleted === true) list[i].deleted = '是'
          }
          excel.export_json_to_excel2(tHeader, list, filterVal, '订单信息')
          this.downloadLoading = false
        })
      })
    },
    logisticsQuery() {
      window.open('http://www.kuaidi100.com/')
    },
    cancelOrder(row) {
      this.$confirm('是否取消订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancalOrder(row.id).then(response => {
          if (response.data.errno === 0) {
            this.$alert('订单取消成功！', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                this.getList()
              }
            })
          } else {
            this.$alert('订单取消失败！', '提示', {
              confirmButtonText: '确定'
            })
          }
        })
      })
    },
    handleChargeCancel() {
      clearTimeout(this.timeOut)
      this.chargeButton = false
      this.dialogChargeFormVisible = false
      this.getList()
    },
    goPay(row) {
      this.walletRecoed.recordSn = this.createRecordSn()
      this.orderSn = this.walletRecoed.recordSn
      this.orderId = row.id
      this.tempOrderSn = row.orderSn
      this.listQuery_1.orderId = this.orderId
      readMechanismUser(this.listQuery_1).then(response => {
        // this.walletRecoed.userId = response.data.data.user.id
        if (response.data.data.num > 0) {
          ordersList(row.id).then(response => {
            this.ordersDetail = response.data.data
            this.tempRetailPrice = this.ordersDetail.orderGoods.price
            this.tempNumber = this.ordersDetail.orderGoods.number
            this.freight = this.ordersDetail.order.freightPrice
            this.walletRecoed.modifyAmount = this.ordersDetail.order.orderPrice
            this.walletRecoed.specifications = this.ordersDetail.orderGoods.specifications.toString()
            this.dialogChargeFormVisible = true
          })
        } else {
          this.$alert('用户不存在', '提示', {
            confirmButtonText: '确定'
          })
        }
      })
    },
    createRecordSn() {
      var date = new Date()
      var Y = date.getFullYear()
      var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      var ss = date.getMilliseconds()
      if (ss < 10) {
        ss = '00' + ss
      } else if (ss < 100) {
        ss = '0' + ss
      }
      return (
        'JG' + Y.toString() + M.toString() + D.toString() + h.toString() + m.toString() + s.toString() + ss.toString()
      )
    },
    handleCharge() {
      modifyOrder({
        beforeOrderSn: this.tempOrderSn,
        orderSn: this.walletRecoed.recordSn,
        orderId: this.orderId
      }).then(response => {
        if (this.walletRecoed.payType === '2') {
          this.chargeButton = true
          this.fullscreenLoading = true
          createUser(this.walletRecoed).then(response => {
            var codeUrl = response.data.data.codeURL
            this.qrConfig.value = codeUrl
            this.qrDialogStatus = true
            this.timeOut = setTimeout(() => {
              this.checkChargeStatus()
            }, 5000)
          })
        } else if (this.walletRecoed.payType === '1') {
          chargeByAliPay(this.walletRecoed)
            .then(response => {
              var data = response.data
              if (data.errno === 0) {
                var codeUrl = data.data
                this.aliQrConfig.value = codeUrl
                this.alipayDialogStatus = true
                this.chargeButton = true
                this.timeOut = setTimeout(() => {
                  this.checkAliPayStatus()
                }, 5000)
              }
            })
            .catch(err => {
              console.log(err)
            })
        }
      })
    },
    checkChargeStatus() {
      if (this.walletRecoed.recordSn !== '') {
        queryalipaystatus({ orderSn: this.orderSn })
          .then(response => {
            var orderStatus = response.data.data.orderStatus
            if (orderStatus === 'SUCCESS') {
              this.qrConfig.value = ''
              this.qrDialogStatus = false
              this.timeOut = ''
              this.dialogChargeFormVisible = false
              this.fullscreenLoading = false
              this.chargeButton = false
              this.$alert('付款成功！', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.getList()
                }
              })
            } else {
              this.timeOut = setTimeout(() => {
                this.checkChargeStatus()
              }, 3000)
            }
          })
      }
    },
    checkAliPayStatus() {
      if (this.walletRecoed.recordSn !== '') {
        queryalipaystatus({ orderSn: this.orderSn })
          .then(response => {
            var orderStatus = response.data.data.orderStatus
            if (orderStatus === 'SUCCESS') {
              this.timeOut = ''
              this.aliQrConfig.value = ''
              this.dialogChargeFormVisible = false
              this.alipayDialogStatus = false
              this.fullscreenLoading = false
              this.chargeButton = false
              this.$alert('付款成功！', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.getList()
                }
              })
            } else if (orderStatus === 'WAIT_PAY') {
              this.timeOut = setTimeout(() => {
                this.checkAliPayStatus()
              }, 3000)
            }
          })
          .catch(() => {
            this.timeOut = ''
            this.dialogChargeFormVisible = false
            this.alipayDialogStatus = false
            this.fullscreenLoading = false
            this.chargeButton = false
            this.$alert('付款失败！', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                this.getList()
              }
            })
          })
      }
    }
  }
}
</script>
